"""
get_h3c_filestorage_quota()函数负责调用华三存储api，将查询结果传入handle_data()函数，然后将数据发送到后端api
"""
# -*- coding:utf-8 -*-


import requests
import datetime
import logging
import json
import re
# import des3

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s : %(levelname)s : %(message)s',
    filename="/home/storage_api.log"
)


# 提取当前时间，整理格式后返回当前时间值，用于生成result_txt
def result_txt_time():
    now = datetime.datetime.now()
    now_time = now.strftime("%Y%m%d%H%M")
    return now_time

result_txt_name = "/home/h3c_log_" + result_txt_time() + ".txt"
# result_txt_name = "D:/h3c_log_" + result_txt_time() + ".txt"
with open(result_txt_name, "a+") as log:
    tplt = "{:<10}\t{:<10}\t{:<10}\t{:<10}\t{:<10}"
    log.write(tplt.format('ip', 'path', 'assigned_volume(G)', 'use_volume(G)', 'residue_volume(G)', chr(255)))
    log.write('\n')


# 使用POST协议将数据发送到对端接口
def send_data_to_api(ip, path, assigned_volume, use_volume, residue_volume):
    
    base_url = "https://地址"

    # request_data格式
    request_data = {
        "ip": ip,
        "path": path,
        "assigned_volume": assigned_volume,
        "use_volume": use_volume,
        "residue_volume": residue_volume
    }

    # 使用POST协议发送数据，并接收返回值
    requests_res = requests.post(
        url=base_url,
        data=json.dumps(request_data)
    )
    requests_res_data = requests_res.json()
    # 记录日志
    # logging.info("execute send_data_to_api path: {0} result: {1}".format(path, requests_res_data))
    return requests_res_data


# 接收调用华三存储API得到的数据，整理每个目录数据的格式，然后调用send_data_to_api()函数发送数据至后端接口，存入数据库
def handle_data(path, size):
    # 生成日志，记录整理后准备发送的数据
    # result_txt_name = "/home/h3c_log_" + result_txt_time() + ".txt"

    with open(result_txt_name, "a+") as log:
        tplt = "{:<10}\t{:<10}\t{:<10}\t{:<10}\t{:<10}"

        ip = "xx"
        path = path
        assigned_volume = round(size / 1024 / 1024 / 1024, 3)
        use_volume = round(size / 1024 / 1024 / 1024, 3)
        residue_volume = 0

        try:
            log.write(tplt.format(ip, path, assigned_volume, use_volume, residue_volume, chr(255)))
            log.write('\n')
            logging.info("execute write path ({0}) successful".format(path))
            send_data_to_api(ip, path, assigned_volume, use_volume, residue_volume)
        except:
            log.write("error\n")
            logging.error("execute write path ({0}) error".format(path))


def get_h3c_cluster_filestorage_dir_stat(x_xsrf_token_value, cookie_value, cluster_id, path):
    # 拼接成登陆url
    base_url = "http://地址"

    # 生成查询URL
    cluster_filestorage_dir_stat_1 = "/api/v3/onestor/"
    cluster_filestorage_dir_stat_2 = "/filestorage/dir/stat"
    cluster_filestorage_dir_stat = base_url + cluster_filestorage_dir_stat_1 + cluster_id + cluster_filestorage_dir_stat_2

    path = '/' + path
    # 请求参数
    request_data = {
        "path": path,
        "type": "directory"
    }

    # 发送post请求，得到返回数据
    cluster_filestorage_dir_stat_res = requests.post(
        url=cluster_filestorage_dir_stat,
        data=json.dumps(request_data),
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': x_xsrf_token_value,
            'Cookie': cookie_value,
        })
    cluster_filestorage_dir_stat_data = cluster_filestorage_dir_stat_res.json()
    # 输出容量
    size = cluster_filestorage_dir_stat_data['data']['size']
    return size


# 调用华三集群的API，返回存储目录及使用情况
def get_h3c_filestorage_dirs():
    # 拼接成登陆url
    base_url = "http://地址"
    request_url = "/api/v1/auth/login"
    url = base_url + request_url

    # 登陆用户名、密码
    data = {"username": "xx", "password": "xx"}

    # 登录请求
    res = requests.post(url=url, data=json.dumps(data), headers={'content-type': "application/json"})

    # 获取响应头信息
    set_cookie = res.headers.get('Set-Cookie')
    text_set_cookie = re.split('[;,=\']', set_cookie)

    # 从响应头信息中提取后面访问需要的cookie_value和x_xsrf_token_value
    xsrf_token_value = text_set_cookie[1].strip()

    cookie_value = 'calamari_sessionid=' + text_set_cookie[12] + ';' + 'XSRF-TOKEN=' + xsrf_token_value

    # 获取集群ID
    cluster_id_api_url = "/api/v3/plat/cluster"
    cluster_id_url = base_url + cluster_id_api_url

    cluster_res = requests.get(
        url=cluster_id_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': xsrf_token_value,
            'Cookie': cookie_value,
        })

    cluster_data = cluster_res.json()
    cluster_id = cluster_data['data']['id']

    # 生成请求URL
    filestorage_dirs_url_1 = "/api/v3/onestor/"
    filestorage_dirs_url_2 = "/filestorage/dirs"
    filestorage_dirs_url = base_url + filestorage_dirs_url_1 + cluster_id + filestorage_dirs_url_2

    # 请求参数
    request_data = {
        # example: "/asp"
        "path": "/",
        "start": 1,
        "filter_file": "all"
    }

    # 发送POST请求，得到返回数据
    filestorage_dirs_res = requests.post(
        url=filestorage_dirs_url,
        data=json.dumps(request_data),
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': xsrf_token_value,
            'Cookie': cookie_value,
        })
    filestorage_dirs_data = filestorage_dirs_res.json()

    for path in filestorage_dirs_data['data']['content']:
        size = get_h3c_cluster_filestorage_dir_stat(xsrf_token_value, cookie_value, cluster_id, path['name'])
        # print(path['name'], size)
        handle_data(path['name'], size)

    # logout登出
    logout_api_url = "/api/v1/auth/logout"
    logout_url = base_url + logout_api_url
    logout_res = requests.get(
        url=logout_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': xsrf_token_value,
            'Cookie': cookie_value,
        })
    return filestorage_dirs_data


if __name__ == '__main__':
    h3c_xd_dict_data = get_h3c_filestorage_dirs()